package com.sx.pipeline.ui.map

import android.Manifest
import android.annotation.SuppressLint
import android.graphics.Point
import android.os.Bundle
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MyLocationStyle
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.permissionx.guolindev.PermissionX
import com.sx.mvvmlibs.binding.edittext.viewAdapter
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseFragment
import com.sx.pipeline.app.model.CYBaseViewModel
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.databinding.FragMapBinding
import com.sx.pipeline.utils.PermissionHelper
import kotlin.math.roundToInt


/**
 * @Author: YY
 * @Date: 2022/4/7
 * @Description: 地图
 */
class MapFragment : CYDataBindingBaseFragment<FragMapBinding, MapVM>(R.layout.frag_map),
    View.OnClickListener, AMap.OnMapClickListener, AMap.OnMarkerClickListener,
    AMap.OnMapTouchListener {

    private lateinit var aMap: AMap

    // 编辑状态
    private var isEditor: Boolean = false

    private lateinit var mPopup: BasePopupView

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mBinding.mapView.onSaveInstanceState(outState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mBinding.mapView.onCreate(savedInstanceState)
        if (!this::aMap.isInitialized) {
            aMap = mBinding.mapView.map
        }
        initMapLocation()
    }

    override fun onResume() {
        super.onResume()
        mBinding.mapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mBinding.mapView.onPause()
    }

    override fun onDestroyView() {
        mBinding.mapView.onDestroy()
        DistrictDrawHelper.clearDraw()
        super.onDestroyView()
    }

    override fun initData() {
        mBinding.setVariable(BR.onClick, this)
    }

    override fun initViewObservable() {
        super.initViewObservable()
        observe(mViewModel.drawTerritoryEvent) {
            isEditor = false
            mBinding.layout1.visibility = View.VISIBLE
            mBinding.layout2.visibility = View.INVISIBLE
            DistrictDrawHelper.clearDraw()
        }
    }


    override fun onClick(v: View) {
        when (v.id) {
            R.id.image_cut -> {
                // 切换图层
            }
            R.id.tv_add_location -> {
                // 申请权限
                PermissionHelper.requestTip(context!!,"添加地址需要授权定位权限",object :
                    PermissionUtils.SimpleCallback{
                    override fun onGranted() {
                        RouteManager.Main.intentToSearchLocation()

                    }

                    override fun onDenied() {
                        ToastUtils.showShort("请授权后再继续操作")
                    }
                },Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS)

//                PermissionX.init(this)
//                    .permissions(
//                        Manifest.permission.ACCESS_FINE_LOCATION,
//                        Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
//                    )
//                    .onExplainRequestReason { scope, deniedList ->
//                        scope.showRequestReasonDialog(
//                            deniedList,
//                            "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                            "确认",
//                            "取消"
//                        )
//                    }
//                    .onForwardToSettings { scope, deniedList ->
//                        scope.showForwardToSettingsDialog(
//                            deniedList,
//                            "您需要手动在“设置”中允许必要的权限",
//                            "确定",
//                            "取消"
//                        )
//                    }
//                    .request { allGranted, grantedList, deniedList ->
//                        if (allGranted) {
//                            RouteManager.Main.intentToSearchLocation()
//                        } else {
//                            Toast.makeText(
//                                context,
//                                "这些权限被拒绝,可能影响管建宝正常使用" + ": $deniedList",
//                                Toast.LENGTH_LONG
//                            ).show()
//                        }
//                    }
            }
            R.id.ll_editor -> {
                // 编辑
                isEditor = true
                mBinding.layout1.visibility = View.INVISIBLE
                mBinding.layout2.visibility = View.VISIBLE
            }
            R.id.ll_delete -> {
                isEditor = false
                mBinding.layout1.visibility = View.VISIBLE
                mBinding.layout2.visibility = View.INVISIBLE
                DistrictDrawHelper.clearDraw()
            }
            R.id.ll_last_step -> {
                // 上一步
                DistrictDrawHelper.lastStep()
            }
            R.id.ll_submit -> {
                // 确定
                if (DistrictDrawHelper.getHasDrawFinish()) {
                    showInputDialog()
                } else {
                    ToastUtils.showShort("请闭合绘制图形")
                }
            }
        }
    }

    /**
     * 初始化地图定位
     */
    private fun initMapLocation() {
        val myLocationStyle = MyLocationStyle()
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
        // 设置连续定位模式下的定位间隔
        myLocationStyle.interval(10000)
        aMap.minZoomLevel
        // 缩放比例
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16f))
        // 设置定位蓝点的Style
        aMap.myLocationStyle = myLocationStyle
        // 设置默认定位按钮是否显示
        aMap.uiSettings.isMyLocationButtonEnabled = true
        // 设置缩放按钮是否显示
        aMap.uiSettings.isZoomControlsEnabled = false
        // 设置比例尺控件是否显示
        aMap.uiSettings.isScaleControlsEnabled = true
        // 关闭旋转手势
        aMap.uiSettings.isRotateGesturesEnabled = false
        // 关闭倾斜手势
        aMap.uiSettings.isTiltGesturesEnabled = false
        // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位
        aMap.isMyLocationEnabled = true
        // 设置地图点击事件
        aMap.setOnMapClickListener(this)
        // 设置Marker标记点击事件
        aMap.setOnMarkerClickListener(this)
        // 地图图层触摸事件
        aMap.setOnMapTouchListener(this)
    }

    @SuppressLint("InflateParams")
    override fun onMapClick(latLng: LatLng) {
        if (isEditor) {
            if (!this::aMap.isInitialized) {
                return
            }
            DistrictDrawHelper.drawPoints(requireContext(), latLng, aMap)
        }
    }

    override fun onMarkerClick(marker: Marker): Boolean {
        DistrictDrawHelper.drawDistrict(marker)
        return true
    }

    override fun onTouch(ev: MotionEvent) {
        DistrictDrawHelper.handleTouchEvent(ev)
    }

    /**
     * 输入名称
     */
    private fun showInputDialog() {
        mPopup = XPopup.Builder(requireContext())
            .autoDismiss(false)
            .asInputConfirm(
                "请输入名称",
                "", "绘制名称"
            ) {
                if (!TextUtils.isEmpty(it)) {
                    mViewModel.addTerritory(it, DistrictDrawHelper.getPointList())
                    mPopup.dismiss()
                } else {
                    ToastUtils.showShort("请输入名称")
                }
            }.also {
                val editText = it.findViewById<EditText>(com.lxj.xpopup.R.id.et_input)
                viewAdapter.filterEditText(editText, true)
            }.show()
    }

}